package cn.tuling.account.controller;


import cn.tuling.account.po.Account;
import cn.tuling.account.service.AccountService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author wuyanzhao
 * @since 2021-12-25
 */
@RestController
@RequestMapping("/account")
public class AccountController {
    @Autowired
    private AccountService accountService;

    @PutMapping("/debit")
    public Boolean debit(@RequestBody Account account) {
        Account qResult = accountService.getOne(new LambdaQueryWrapper<Account>().eq(Account::getUserId, account.getUserId()));
        if (qResult == null)
            throw new RuntimeException("该用户没有余额");
        if (qResult.getMoney().compareTo(account.getMoney()) < 0)
            throw new RuntimeException("该用户余额不足");

        return accountService.update(new LambdaUpdateWrapper<Account>()
                .eq(Account::getUserId, account.getUserId())
                .set(Account::getMoney, qResult.getMoney().subtract(account.getMoney())));
    }
}

